import { CdkDrag } from '@angular/cdk/drag-drop';
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Subscription } from 'rxjs';
import { AssemblyDrawingViewService } from '@core/services/assemblyDrawing/assemblyDrawing.view.service';

@Component({
  templateUrl: './cad-image-content.component.html',
  selector: 'cad-image-content',
  styleUrls: ['./cad-image-content.component.scss'],
})

export class CadImageContentComponent implements OnInit, OnDestroy {

  @ViewChild(CdkDrag, { static: true }) cdkDrag: CdkDrag;

  images = [];
  imgW: any;
  imgH: any;
  points = [];
  currentImg: string = '';
  oldSelect: any;
  selectImg: any = 0;
  isLoading: boolean = false;

  style = {};
  zoom: number = 1;


  private subscription: Subscription;
  private selectPartsSubscription: Subscription;

  constructor(
    private assemblyDrawingViewService: AssemblyDrawingViewService,
  ) {

  }

  ngOnInit(): void {
    this.subscription = this.assemblyDrawingViewService.imgSelectChange$.subscribe((data: any) => {

      if (data && data.imgs.length != 0) {
        this.images = data.imgs;
        this.points = this.images[0]['points'];
        this.currentImg = this.images[0].url;
        this.initImg();
      } else {
        this.images = [];
        this.currentImg = '';
        this.points = [];
      }
    });
    this.selectPartsSubscription = this.assemblyDrawingViewService.selectPart$.subscribe((data: any) => {
      // console.log('选中配件行',data);
      if (this.oldSelect != data) {
        this.oldSelect = data;
        this.checkPart(data);
      }
    });
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
    this.selectPartsSubscription.unsubscribe();
  }

  initImg() {
    this.isLoading = true;
    setTimeout(() => {
      let img = document.getElementById('oImg');
      this.loadImg(img, (res) => {
        // console.log(res);
        this.imgW = res.w;
        this.imgH = res.h;
        this.reset();
      });
    }, 100);
  }

  reset() {
    // this.zoom = 0.45;
    let _body = document.querySelector('.drag-container');
    this.zoom = Math.floor((_body.clientWidth / this.imgW) * 100) / 100;
    // console.log(_body);
    this.cdkDrag.reset();
    this.cdkDrag.getRootElement().style.transform = `translate3d(0px, 0px, 0px) scale(${this.zoom})`;
    this.isLoading = false;
  }

  // 切换当前显示的图片
  toggleImg(image,index) {
    this.currentImg = image.url;
    this.points = image['points'];
    this.selectImg = index;
    this.initImg();
  }

  zoomOut() {
    this.zoom += 0.1;
    if (this.zoom <= 0.3) {
      this.zoom = 0.3;
    }
    const pos = this.cdkDrag.getFreeDragPosition();
    // console.log('放大--', pos.x, pos.y, this.zoom);
    // this.cdkDrag.getRootElement().style.transformOrigin = `center center`;
    // this.cdkDrag.getRootElement().style.transform = `scale(${this.zoom})`;
    this.cdkDrag.getRootElement().style.transform = `translate3d(${pos.x}px, ${pos.y}px, 0px) scale(${this.zoom})`;
  }

  zoomIn() {
    this.zoom -= 0.1;
    if (this.zoom <= 0.3) {
      this.zoom = 0.3;
    }
    const pos = this.cdkDrag.getFreeDragPosition();
    // console.log('缩小--', pos.x, pos.y, this.zoom);
    // this.cdkDrag.getRootElement().style.transformOrigin = `center center`;
    // this.cdkDrag.getRootElement().style.transform = `scale(${this.zoom})`;
    this.cdkDrag.getRootElement().style.transform = `translate3d(${pos.x}px, ${pos.y}px, 0px) scale(${this.zoom})`;
  }

  dragStart() {
    const pos = this.cdkDrag.getFreeDragPosition();
    // console.log('拖动--', pos.x, pos.y, this.zoom);
    this.cdkDrag.getRootElement().style.transform = `translate3d(${pos.x}px, ${pos.y}px, 0px) scale(${this.zoom})`;
  }

  zoomInAndOut($evnet) {
    const target: HTMLImageElement = $evnet.target;
    const pos = this.cdkDrag.getFreeDragPosition();

    this.zoom += $evnet.wheelDelta / 12 / 100;
    if (this.zoom <= 0.3) {
      this.zoom = 0.3;
    }
    // this.style = {transform:`scale(${this.zoomIn})`};

    // let ratioL = ($evnet.clientX - pos.x) / this.imgW;
    // let ratioT = ($evnet.clientY - pos.y) / this.imgH;
    // let w = parseInt((this.imgW * this.zoom) + '');
    // let h = parseInt((this.imgH * this.zoom) + '');
    // let cdk = {
    //   w: w,
    //   h: h,
    //   x: Math.round($evnet.clientX - w),
    //   y: Math.round($evnet.clientY - h),
    // x: ($evnet.offsetX - (($evnet.offsetX - pos.x)/this.imgW)*this.zoom),
    // y: ($evnet.offsetY - (($evnet.offsetY - pos.y)/this.imgH)*this.zoom),
    // };
    // this.cdkDrag.getRootElement().style.width = `${cdk.w}`;
    // this.cdkDrag.getRootElement().style.height = `${cdk.h}`;
    // this.cdkDrag.getRootElement().style.left = `${cdk.x}`;
    // this.cdkDrag.getRootElement().style.top = `${cdk.y}`;
    // console.log(
    //   '滚轮--', pos.x, pos.y, this.zoom,
    //   '鼠标--', $evnet.offsetX, $evnet.offsetY,
    //   '图片--', this.imgW, this.imgH,
    //   '实际--', cdk.x,cdk.y
    // );
    // this.cdkDrag.getRootElement().style.transform = `translate3d(${cdk.x}px, ${cdk.y}px, 0px) scale(${this.zoom})`;
    this.cdkDrag.getRootElement().style.transform = `translate3d(${pos.x}px, ${pos.y}px, 0px) scale(${this.zoom})`;
    return false;
  }

  checkPart(sn){
    let _sn = sn.replace(/[()]/g, '');
    let index = -1 ;
    for (let i = 0; i < this.images.length; i++) {
      this.images[i]['points'].forEach((p) => {
        let psn = p['sn'].replace(/[()]/g, '');
        if (psn == _sn) {
          p['activate'] = true;
          if(index == -1){
            index = i;
          }
        } else {
          p['activate'] = false;
        }
      });
    }

    if(index == -1){
      index = 0;
    }

    this.currentImg = this.images[index].url;
    this.points = this.images[index]['points'];
    this.selectImg = index;
    // this.initImg();
  }

  checkRect(sn) {
    let _sn = sn.replace(/[()]/g, '');
    for (let i = 0; i < this.images.length; i++) {
      this.images[i]['points'].forEach((p) => {
        let psn = p['sn'].replace(/[()]/g, '');
        if (psn == _sn) {
          p['activate'] = true;
        } else {
          p['activate'] = false;
        }
      });
    }

    this._scrollTo(_sn);

    this.assemblyDrawingViewService.selectPartImg$.next(_sn);
  }

  _scrollTo(id) {
    let _id = document.getElementById(id);
    if (_id) {
      let _body = document.querySelector('.apes-table-body');
      _body.scrollTo(0, _id.offsetTop);
    }
  }

  loadImg(oImg, callback) {
    let nWidth, nHeight;
    if (!oImg.naturalWidth) { // 现代浏览器

      nWidth = oImg.naturalWidth;
      nHeight = oImg.naturalHeight;
      callback({ w: nWidth, h: nHeight });

    } else { // IE6/7/8
      let nImg = new Image();

      nImg.onload = () => {
        let nWidth = nImg.width,
          nHeight = nImg.height;
        callback({ w: nWidth, h: nHeight });
      };
      nImg.src = oImg.src;
    }
  }

}
